import React from 'react';
import { inject, observer } from 'mobx-react';
import { routerShape } from 'react-router';
import { Condition, getAdButtons } from '../list/listCondition';
import { WeaErrorPage, WeaTools, WeaTop, WeaTab, WeaRightMenu, WeaProgress, WeaLocaleProvider } from 'ecCom';
import { Button } from 'antd';
import { toJS } from "mobx"
import { WeaTableNew } from 'comsMobx';
import ShareDialog from '../dialog/shareDialog'
import ExchangeDialog from '../dialog/exchangeDialog'
import TaskInfoDialog from '../dialog/taskDialog'

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

@inject("queryTaskStore")
@observer
class QueryTaskResult extends React.Component {
    static contextTypes = {
        router: routerShape
    }
    constructor(props) {
        super(props);
        this.doInit(this.props);
        this.state = {
            workPlanVisible: false,
            coWorkVisiable: false,
            taskid: "",
            projectid: ""
        }
    }

    doInit(props) {
        const { location:{query},queryTaskStore, location } = props;
        //我的任务（门户元素）更多
        if(query.searchfrom==='portal'){
            queryTaskStore.getQueryCondition();
            queryTaskStore.setSearchfrom();
        }
        queryTaskStore.doSearch(query);
    }
    componentDidMount() {
        const { queryTaskStore } = this.props;
        // if (!window.weaWorkplan) {
        //     // 异步加载别模块的静态资源
        //     eventRegister.loadModule('f_workplan', () => {
        //         queryTaskStore.setLoaded(true)
        //     }, () => {
        //         // 加载文件失败 的业务处理， 网络超时，没文件之类
        //     })
        // } else {
        //     queryTaskStore.setLoaded(true)
        // }

        if (!window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_workplan', () => {
                eventRegister.loadModule('f_cowork', () => {
                    queryTaskStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载日程模块失败，请联系系统管理员！");
            });
            return;
        }
        if (window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_cowork', () => {
                queryTaskStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        } else {
            eventRegister.loadModule('f_workplan', () => {
                queryTaskStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        }
    }
    componentWillUnmount() {
        const { queryTaskStore } = this.props;
        queryTaskStore.clearStatus();
    }
    render() {
        let _this = this;
        const { location:{query},queryTaskStore } = this.props;
        const { loading, form, tableStore, showSearchAd, exchangeStore, taskInfoStore, reLoad } = queryTaskStore;
        const formParams = form.getFormParams();    //Mobx-form的Bug，form传给子组件时需外层调用下取值，否则查询条件变了组件不会render
        const account = WeaTools.ls.getJSONObj('theme-account');
        return (
            <div className='prj-query'>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@4x2dr5`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jg9x3e`}
                        title={query.searchfrom==='portal' ? getLabel(244571, "我的任务"):getLabel(24457, "查询任务")}
                        loading={loading}
                        icon={<i className='icon-coms-project' />}
                        iconBgcolor='#217346'
                        buttons={this.getTopButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()} onDropMenuClick={this.onRightMenuClick.bind(this)}
                    >
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@7cxat9`}
                            buttonsAd={getAdButtons(queryTaskStore,this.props.ecId || '')}
                            searchType={['base', 'advanced']}
                            searchsBaseValue={formParams.taskname}
                            setShowSearchAd={bool => { queryTaskStore.setShowSearchAd(bool) }}
                            hideSearchAd={() => queryTaskStore.setShowSearchAd(false)}
                            searchsAd={
                                <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@18fzoy`} listStore={queryTaskStore} form={form} onEnterSearch={this.onEnterSearch} ></Condition></div>
                            }
                            showSearchAd={showSearchAd}
                            onSearch={v => { queryTaskStore.doSearch() }}
                            onSearchChange={v => { queryTaskStore.appendFormFields({ taskname: { value: v } }) }}
                        />
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@yrvoub`}
                            comsWeaTableStore={tableStore}
                            hasOrder={true}
                            needScroll={true}
                            register_table={() => reLoad()}
                            getColumns={c => this.reRenderColumns(c)}
                            tableWidth={this.tableWidth}
                            onOperatesClick={this.onOperatesClick.bind(this)}
                        />
                    </WeaTop>
                    {window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.coWorkVisiable && this.state.taskid !== "" && (
                        <window.weaCowork.com.CreateCowork ecId={`${this && this.props && this.props.ecId || ''}_CreateCowork@orakom`}
                            initAddQuery={
                                {
                                    relatedType: "task",
                                    ids: this.state.taskid
                                }
                            }
                            onCancel={() => {
                                this.setState({
                                    coWorkVisiable: false
                                });
                            }}
                        />)
                    }
                    {
                        queryTaskStore.isreloadWorkPlan && window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
                        (<window.weaWorkplan.com.WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@o0cp37`}
                            type={"create"}//新建为'create',查看为'preview',编辑edit,共享share
                            visible={_this.state.workPlanVisible}//显隐受控
                            doClose={() => { _this.setWorkPlanVisible(false); }}//关闭回调
                            onlyClose={() => { _this.setWorkPlanVisible(false) }}//关闭回调,只做关闭操作
                            workPlanId={""} //日程id，1查看日程时用到
                            createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                            activeKey={""} //查看页面显示的面板1是基本信息，7是相关交流
                            //{(key) => { }}//查看页面切换面板的回调
                            selectUser={account && account.userid}//新建日程的创建人id
                            workPlanTypeOptions={"2"}//客户模块的新建日程，普通新建传'',客户新建传3
                            projectid={_this.state.projectid}
                            taskid={_this.state.taskid}
                            description={""}//客户模块需求，支持新建时传入的'基本信息-内容'
                        />)
                    }
                    <ShareDialog ecId={`${this && this.props && this.props.ecId || ''}_ShareDialog@im5baw`} contentStore={queryTaskStore} />
                    <ExchangeDialog ecId={`${this && this.props && this.props.ecId || ''}_ExchangeDialog@bz3n97`} contentStore={exchangeStore} />
                    <TaskInfoDialog ecId={`${this && this.props && this.props.ecId || ''}_TaskInfoDialog@n0bic6`} contentStore={taskInfoStore} />
                </WeaRightMenu>
            </div>
        )
    }

    setWorkPlanVisible = (bool) => {
        this.setState({ workPlanVisible: bool })
    }

    getTopButtons() {
        const { queryTaskStore } = this.props;
        const { rightMenu, tableStore } = queryTaskStore;
        let { selectedRowKeys } = tableStore;
        let btnArr = [];
        let that = this;
        const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
        rightMenu && rightMenu.length > 0 && toJS(rightMenu).map(m => {
            let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
            m.isTop == '1' && btnArr.length < 4 && btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hbkh93@${m.type}`} type="primary"
                    disabled={isDisabled && m.isControl == "1"}
                    onClick={() => {
                        if (fn == "") {
                            if (m.type == "BTN_EXPORT") { //导出Excel
                                queryTaskStore.doTaskExcelExp();
                            }
                        }
                    }}>
                    {m.menuName}
                </Button>
            );
        });
        return btnArr;
    }
    getRightMenu() {
        const { queryTaskStore } = this.props;
        const { rightMenu } = queryTaskStore;
        let btnArr = [];
        rightMenu && rightMenu.length > 0 && rightMenu.map(m => {
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName
            })
        });
        return btnArr
    }
    onRightMenuClick(key) {
        const { queryTaskStore } = this.props;
        const { rightMenu } = queryTaskStore;
        let that = this;
        rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
            if (Number(key) == i) {
                if (m.type == "BTN_COLUMN") { //定制列
                    queryTaskStore.onShowColumn();
                } else if (m.type == "BTN_EXPORT") {
                    queryTaskStore.doTaskExcelExp();
                }
            }
        });
    }
    reRenderColumns(columns) {
        columns.forEach((c,i) => {
            if (c.dataIndex == 'finish') {
                c.render = function (text, record) {
                    return <span className='wea-prj-progressStyle' >
                        <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@a27iyi@${i}`} percent={record.finish || 0} strokeColor={record.finishspan} />
                    </span>
                }
            } else {
                c.render = function (text, record) {
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    return <span dangerouslySetInnerHTML={{ __html: valueSpan }}></span>
                }
            }
        })
        return columns;
    }
    
    tableWidth = (columns) => {
        let width = 0;
        let cols = 0;
        columns.map(col => {
          if (col.display === 'true') {
            let oldwidth = col.oldWidth || '10%';
            let widthInt = parseFloat(oldwidth.replace('%', ''));
            if (widthInt <= 0) {
              widthInt = 10;
            }
            width += widthInt;
            cols++
          }
        })
        //超过10列，才出现滚动条，width>100才出现滚动条
        if(cols<=10){
            width = 100 ;
        }
        return `${width}%`;
    }

    onOperatesClick(record, index, operate, flag) {
        let that = this;
        const { queryTaskStore } = this.props;
        const { shareStore, exchangeStore, taskInfoStore } = queryTaskStore;

        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:", "");
        fn = fn.substring(0, fn.indexOf('('));
        if (fn != "") {
            if ("onShare" == fn) {  //共享
                shareStore.handleShareDialog(true, "task", record.randomFieldId, {})
            } else if ('onNewCowork' == fn) {   //新建协作
                this.setState({ coWorkVisiable: true, taskid: record.randomFieldId, projectid: record.prjid })
                const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
                const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
                cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
            } else if ('onNewWorkplan' == fn) {   //新建日程
                this.setState({ workPlanVisible: true, taskid: record.randomFieldId, projectid: record.prjid })
            } else if ('onEdit' == fn) {   //编辑
                taskInfoStore.handleDialog(true, "edit", record.randomFieldId);
            } else if ('onDiscuss' == fn) {   //相关交流
                exchangeStore.handleExchangeDialog(true, "task", record.randomFieldId, {})
            } else if ('onDel' == fn) {   //删除
                taskInfoStore.delTask("del", record.randomFieldId);
            }
        }
    }

    onEnterSearch=() =>{
        const { queryTaskStore } = this.props;
        queryTaskStore.doSearch();
        queryTaskStore.setShowSearchAd(false);
    } 

}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@7sxo8e`} msg={props.error ? props.error : getLabel(383324, "对不起，该页面异常，请联系管理员")} />,
    { error: "" }
)(QueryTaskResult);